package com.vmc.util;

import java.io.File;

import com.vmc.model.TVTransferDetail;

public class TVDestinationPathLocator {
	private static final String OTHERS = "Others";
	private static final String SEASON = "Season %s";
	private static TVDestinationPathLocator instance = new TVDestinationPathLocator();
	
	private TVDestinationPathLocator() {
		
	}
	
	public static TVDestinationPathLocator getInstance() {
		return instance;
	}
	
	public File getLocation(File source, TVTransferDetail detail) {
		return this.getLocation(source, detail, false);
	}
	
	public File getLocation(File source, TVTransferDetail detail, boolean willCreate) {
		return this.getLocation(source, detail, willCreate, false);
	}
	
	private File getLocation(File source, TVTransferDetail detail, boolean willCreate, boolean hasTitle) {
		File location = null;
		
		if (source != null && source.isDirectory() && detail != null) {
			for (File item : source.listFiles()) {
				if (item.isDirectory()) {
					if (!hasTitle) {
						location = getLocation(item, detail, willCreate, (item.getName().equals(detail.getTitle())) ? true : hasTitle);
					}
					else {
						if (item.getName().equals(String.format(SEASON, detail.getSeason()))) {
							return location = item;
						}
					}
				}
			}
		}
		
		if (location == null && willCreate) {
			location = this.createLocation(source, detail);
		}
		
		return location;
	}
	
	private File createLocation(File source, TVTransferDetail detail) {
		File location = null;
		
		if (source != null && source.isDirectory()) {
			location = new File(source.getAbsolutePath() + File.separator + OTHERS + File.separator + detail.getTitle() + File.separator + detail.getSeason());
			this.createLocation(location);
		}
		
		return location;
	}
	
	private boolean createLocation(File location) {
		if (!location.getParentFile().exists()) {
			this.createLocation(location.getParentFile());
		}
		return location.mkdir();
	}
}
